package fr.loof.fonzie.parsers;

import java.util.List;
import java.util.ListIterator;

import org.apache.commons.lang.StringUtils;

import fr.loof.fonzie.keywords.Equals;

public class Property
    implements QueryElement
{
    private static KeyWord EQUALS = new Equals();

    private String name;

    Property( String name )
    {
        this.name = StringUtils.uncapitalize( name );
    }

    public String toString()
    {
        return name;
    }

    public void process( JPQLPersistenceQuery jpqlQuery, List<Class> params )
    {
        jpqlQuery.append( " " )
                 .append( jpqlQuery.getCurrentEntityShortName() )
                 .append( "." )
                 .append( name );
        jpqlQuery.setCurrentProperty( name );
    }

    public boolean postProcess( ListIterator<QueryElement> elements )
    {
        if ( hasNoConstraint( elements ) )
        {
            elements.add( EQUALS );
        }
        return true;
    }

    private boolean hasNoConstraint( ListIterator<QueryElement> elements )
    {
        if ( !elements.hasNext() )
        {
            return true;
        }
        QueryElement next = elements.next();
        elements.previous();

        if ( next instanceof Constraint )
        {
            return false;
        }
        return true;
    }

    public String getName()
    {
        return name;
    }
}